package cn.edu.scau.common.utils;

import cn.edu.scau.common.setting.IShiroConst;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.apache.commons.lang3.StringUtils;

/**
 * @description: 用token存储UID的工具类
 * @author: yuxiang
 * @create: 2021-02-05 23:29
 **/
public class TokenUserRedisUtils {

    //缓存
    private static CacheManager cacheManager = CacheManager.newInstance();
    private static Long viewArticleTime = System.currentTimeMillis();

    private static Ehcache cache = cacheManager.getEhcache("userIdToken");
    private static Element element;

    public static boolean isExistedKey(String token) {
        if (StringUtils.isEmpty(token))
            return false;
        try {
            //查询缓存
            element = cache.get(token);
            if (element!=null){
                System.out.println("查询uID缓存===》》》token="+token);
                Integer value = (Integer) element.getObjectValue();
                System.out.println("uID缓存" + value);
                if (value!=null) {
                    return true;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    public static Integer getValueByKey(String token) {
        if (StringUtils.isEmpty(token))
            return null;
        try{
            //查询缓存
            element = cache.get(token);
            if (element!=null){
                return (Integer) element.getObjectValue();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void setToken(Integer uid,String token) {
        if (uid == null || StringUtils.isEmpty(token)) {
            return;
        }
        try {
            //设置缓存
            Element e = new Element(token,uid);
            //设置存活时间
            e.setTimeToLive(IShiroConst.EXPIRE_TIME);
            cache.put(e);
            element = cache.get(token);
            //查询缓存
            Integer value2 = (Integer) element.getObjectValue();
            System.out.println(token+"设置UID缓存"+value2);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void delToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return;
        }
        try {
            //查询缓存
            element = cache.get(token);
            System.out.println(element+"删除uid");
            System.out.println("删除uid"+element.getObjectKey());
            if (element!=null){
                //如果缓存不为空
                //删除缓存
                cache.remove(token);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
